import * as types from 'store/mutation-types'
import Vue from 'vue'
import Store from 'store'
import utils from 'commons/utils'

/**
 * 初始化微信SDK
 */
const initWeChat = function () {
    if (!utils.isWeChat()) {
        console.warn('非微信运行环境，初始化微信JSAPI失败')
        return
    }
    getWechatInitConfig().then((data) => {
        Vue.wechat.config({
            debug: false,
            appId: data.appId, // 必填，公众号的唯一标识
            timestamp: data.timestamp + '', // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature,// 必填，签名，见附录1
            jsApiList: [    // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'onMenuShareQZone',
                'chooseWXPay',
                'scanQRCode'
            ]
        });
        Vue.wechat.ready(function () {
            console.log('wechat ready success')
            Store.commit(types.UPDATE_WECHAT_INITD_STATUS, true)
        });
        Vue.wechat.error(function (res) {
            console.error('wechat ready error', res)
        })
    }).catch((err) => {
        console.warn('获取微信JSAPI初始化参数失败：', err)
    })
}

/**
 * 初始化分享接口
 * @param opts 分享參數
 * {
 *  title: xxx,     // 分享标题
 *  link: xxx,      // 分享链接
 *  imgUrl: xxx     // 分享图片
 * }
 */
const initShare = function (opts) {
    if (!utils.isWeChat()) {
        return
    }
    Vue.wechat.onMenuShareTimeline({    //分享到朋友圈
        title: opts.desc,
        link: opts.link,
        imgUrl: opts.imgUrl,
        success: function () {
            Store.commit(types.UPDATE_TIP, '分享成功')
        },
        cancel: function () {
            console.warn('onMenuShareTimeline share error')
        }
    })

    Vue.wechat.onMenuShareAppMessage({  //分享给朋友
        title: opts.title,
        desc: opts.desc, // 分享描述
        link: opts.link,
        imgUrl: opts.imgUrl,
        type: 'link', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        success: function () {
            Store.commit(types.UPDATE_TIP, '分享成功')
        },
        cancel: function () {
            console.log('onMenuShareAppMessage share error')
        }
    })

    Vue.wechat.onMenuShareQQ({  //ios分享到QQ
        title: opts.title,
        desc: opts.desc,
        link: opts.link,
        imgUrl: opts.imgUrl,
        success: function () {
            Store.commit(types.UPDATE_TIP, '分享成功')
        },
        cancel: function () {
            console.log('onMenuShareQQ share error')
        },
        fail: function (msg) {
            console.error('onMenuShareQQ share fail', msg)
        }
    })

    Vue.wechat.onMenuShareQZone({   //ios分享到QQ空间
        title: opts.title,
        desc: opts.desc,
        link: opts.link,
        imgUrl: opts.imgUrl,
        success: function () {
            Store.commit(types.UPDATE_TIP, '分享成功')
        },
        cancel: function () {
            console.log('onMenuShareQZone share error')
        },
        fail: function (msg) {
            console.error('onMenuShareQZone share fail', msg)
        }
    })

    Vue.wechat.onMenuShareWeibo({   //分享到腾讯微博
        title: opts.title,
        desc: opts.desc,
        link: opts.link,
        imgUrl: opts.imgUrl,
        success: function () {
            Store.commit(types.UPDATE_TIP, '分享成功')
        },
        cancel: function () {
            console.warn('onMenuShareWeibo share error')
        }
    })
}

/**
 * 获取微信JS API初始化参数
 * @param cbSuccess
 * @param cbError
 */
const getWechatInitConfig = function () {
    let url = location.href.split('#')[0]
    return Vue.http.get('wechat/jsconfig', {
        params: { surl: url }
    }).then((resp) => {
        return resp.data
    }, (error) => {
        return Promise.reject(error)
    })
}

/**
 * 发送支付请求
 * @param config
 */
const sendPaymentRequest = function (config) {
    return new Promise(function (resolve, reject) {
        Vue.wechat.chooseWXPay({
            appId: config.appId,
            timestamp: config.timeStamp,
            nonceStr: config.nonceStr,
            package: config.package,
            signType: config.signType,
            paySign: config.paySign, // 支付签名
            success(res) {
                console.log('支付结果：', res)
                if(res.errMsg == 'chooseWXPay:ok'){
                    resolve('支付成功');
                } else {
                    reject('支付失败')
                }
            },
            cancel(res) {
                console.log('pay cancel：', res)
                Store.commit(types.UPDATE_TIP, '取消支付')
            }
        })
    })
}

const scanQRCode = function() {
    return new Promise(function(resolve, reject) {
        Vue.wechat.scanQRCode({
            needResult: 1,  // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
            scanType: ["qrCode","barCode"],     // 可以指定扫二维码还是一维码，默认二者都有
            success(res) {
                console.log('scan qrcode result: ', res)
                if (res.errMsg == 'scanQRCode:ok') {
                    resolve(res.resultStr)
                } else {
                   reject(res.errMsg)   // 当needResult为1时，扫码返回的结果
                }
            }
        })
    })
}

export default {
    initWeChat,
    initShare,
    getWechatInitConfig,
    sendPaymentRequest,
    scanQRCode
}
